//
//  MainViewController.m
//  新项目
//
//  Created by 吴品泽 on 15/4/2.
//  Copyright (c) 2015年 吴品泽. All rights reserved.
//

#import "MainViewController.h"
#import <AFHTTPRequestOperationManager.h>
#import <UIImageView+WebCache.h>
#import "TravelTableViewCell.h"
#import "Travelnote.h"
#import "SpeacialTableViewCell.h"
#import "Special.h"
#import "DetailViewController.h"
#import "ZuantiDetailViewController.h"
#import "UserViewController.h"
//上拉加载下拉刷新
#import "MJRefresh.h"


//相机
#import "TakeViewController.h"
@interface MainViewController ()<UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,retain)UIView *buttonView;
@property (nonatomic,retain)UIButton *leftButton;
@property (nonatomic,retain)UIButton *rightButton;
@property (nonatomic,retain)UIView *backView;


@property (nonatomic,retain)UIView *view1;
@property (nonatomic,retain)UITableView *tableview1;
@property (nonatomic,retain)NSMutableArray *arr1;

@property (nonatomic,retain)UIView *view2;
@property (nonatomic,retain)UITableView *tableview2;
@property (nonatomic,retain)NSMutableArray *arr2;

//tableView1的头视图
@property (nonatomic,retain)UIView *headView;


@property (nonatomic,assign)NSInteger shu;
@property (nonatomic,assign)NSInteger shu1;

//@property (nonatomic, strong) TravelCell *traveCell;

@end

@implementation MainViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.navigationController.navigationBar.barTintColor = [UIColor colorWithRed:153 / 255.0 green:204 / 255.0 blue:255 / 255.0 alpha:1];
    self.shu = 2;
    self.shu1 = 2;
    self.arr1 = [NSMutableArray array];
    self.arr2 = [NSMutableArray array];
    [self createTwoButton];
    [self createView1AndView2];
    [self createTableView1AndTableView2];
    [self createRefreash];
   
      // [self requestForTableView1];
    
    
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"iconfont-xiangji.png"] style:UIBarButtonItemStylePlain target:self action:@selector(OpenXiangji:)];
    // 注册
}


- (void)OpenXiangji:(UIBarButtonItem *)item
{
    TakeViewController *takeVC = [[TakeViewController alloc] initWithNibName:@"TakeViewController" bundle:nil];
    [self presentViewController:takeVC animated:YES completion:nil];
    
}







//创建精选顶部的两个button
- (void)createTwoButton
{
    //按钮的底部视图
    self.buttonView = [[UIView alloc]initWithFrame:CGRectMake(0,64,WIDTH, 40)];
    self.buttonView.userInteractionEnabled = YES;
    //self.buttonView.backgroundColor = [UIColor yellowColor];
    UIView  *underButtonView = [[UIView alloc]initWithFrame:CGRectMake(10, 5, WIDTH - 20, self.buttonView.frame.size.height - 10)];
    underButtonView.layer.masksToBounds = YES;
    underButtonView.layer.cornerRadius = 5;
    underButtonView.userInteractionEnabled = YES;
    //左侧按钮的设置
    self.leftButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.leftButton.frame = CGRectMake(0, 0, underButtonView.frame.size.width / 2, underButtonView.frame.size.height);
    [self.leftButton setTitle:@"游记" forState:UIControlStateNormal];
    //self.leftButton.layer.masksToBounds = YES;
   // self.leftButton.layer.cornerRadius = 5;
    
    //右侧按钮的设置
    self.rightButton = [UIButton buttonWithType:UIButtonTypeSystem];
    self.rightButton.frame = CGRectMake(underButtonView.frame.size.width / 2, 0, underButtonView.frame.size.width / 2, underButtonView.frame.size.height);
    [self.rightButton setTitle:@"专题" forState:UIControlStateNormal];
    
    self.rightButton.tintColor = [UIColor blackColor];
    self.leftButton.tintColor = [UIColor colorWithRed:153 / 255.0 green:204 / 255.0 blue:255 / 255.0 alpha:1];;
    
    
    self.backView = [[UIView alloc]initWithFrame:CGRectMake(1, 1, underButtonView.frame.size.width / 2 - 1, underButtonView.frame.size.height - 2)];
    self.backView.userInteractionEnabled = YES;
    self.backView.layer.masksToBounds = YES;
    self.backView.layer.cornerRadius = 5;
    
    self.backView.backgroundColor = [UIColor whiteColor];
    underButtonView.backgroundColor = [UIColor colorWithRed:230 / 255.f green:230 / 255.f blue:230 / 255.f alpha:1];
    
   // self.buttonView.backgroundColor = [UIColor yellowColor];
    //self.leftButton.backgroundColor = [UIColor purpleColor];
   // self.rightButton.backgroundColor = [UIColor redColor];
   // self.leftButton.alpha = 0;
    //self.rightButton.alpha = 0;
    
    
    
    [self.leftButton addTarget:self action:@selector(appreView1:)forControlEvents:UIControlEventTouchUpInside];
    
    [self.rightButton addTarget:self action:@selector(appreView2:)forControlEvents:UIControlEventTouchUpInside];
    
    
    [self.view addSubview:self.buttonView];
    [self.buttonView addSubview:underButtonView];
    [underButtonView addSubview:self.backView];
    [underButtonView addSubview:self.leftButton];
    [underButtonView addSubview:self.rightButton];
}


- (void)appreView1:(UIButton *)leftbutton
{
   // NSLog(@"111");
    self.rightButton.tintColor = [UIColor blackColor];
    self.leftButton.tintColor = [UIColor colorWithRed:153 / 255.0 green:204 / 255.0 blue:255 / 255.0 alpha:1];
    [UIView animateWithDuration:0.5 animations:^{
        self.backView.center = self.leftButton.center;
    }];
    
    [UIView animateWithDuration:0.5 animations:^{
        self.view2.frame = CGRectMake(WIDTH, 104, WIDTH, HIGHT - 104 - 49);
        self.view1.frame = CGRectMake(0, 104, WIDTH, HIGHT - 104 - 49);
    }];
}


- (void)appreView2:(UIButton *)rightbutton
{
//  NSLog(@"222%f",self.tabBarController.tabBar.frame.size.heigh
        self.rightButton.tintColor = [UIColor colorWithRed:153 / 255.0 green:204 / 255.0 blue:255 / 255.0 alpha:1];
    self.leftButton.tintColor = [UIColor blackColor];
    [UIView animateWithDuration:0.5 animations:^{
        self.backView.center = self.rightButton.center;
        
        [UIView animateWithDuration:0.5 animations:^{
            self.view1.frame = CGRectMake(- WIDTH, 104, WIDTH, HIGHT - 104 - 49);
            self.view2.frame = CGRectMake(0, 104, WIDTH, HIGHT - 104 - 49);
        }];
        
    }];
}


//创建view1 和view2 来装两个tableview

- (void)createView1AndView2
{
    self.view1 = [[UIView alloc]initWithFrame:CGRectMake(0, 104, WIDTH, HIGHT - 104 - 49)];
    self.view1.backgroundColor = [UIColor purpleColor];
    
    
    self.view2 = [[UIView alloc]initWithFrame:CGRectMake(WIDTH, 104, WIDTH, HIGHT - 104 - 49)];
   // self.view2.backgroundColor = [UIColor redColor];
    
    
    [self.view addSubview:self.view1];
    [self.view addSubview:self.view2];
    
}

- (void)createTableView1AndTableView2
{
    self.tableview1 = [[UITableView alloc]initWithFrame:self.view1.bounds style:UITableViewStylePlain];
    self.tableview1.delegate = self;
    self.tableview1.dataSource = self;
  //  [self.tableview1 registerNib:[UINib nibWithNibName:@"TravelCell" bundle:[NSBundle mainBundle]] forCellReuseIdentifier:@"travelCell"];
    self.tableview1.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view1 addSubview:self.tableview1];
    
    
    self.tableview2 = [[UITableView alloc]initWithFrame:self.view2.bounds style:UITableViewStylePlain];
    self.tableview2.delegate = self;
    self.tableview2.dataSource = self;
    self.tableview2.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view2 addSubview:self.tableview2];

    
}


- (void)requestForTableView1
{
    NSString *string = @"https://chanyouji.com/api/trips/featured.json?page=1";
    //NSMutableArray *arrs = [NSMutableArray array];
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    [manager GET:string parameters:self success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        for (NSMutableDictionary *dic in responseObject) {
            Travelnote *note = [[Travelnote alloc]init];
            [note setValuesForKeysWithDictionary:dic];
            [self.arr1 addObject:note];
        }
//        for (NSInteger i = arrs.count; i > 0; i--) {
//            Travelnote *nos = [arrs objectAtIndex:i - 1];
//            [self.arr1 addObject:nos];
//        }
        
     //   NSLog(@"%ld",self.arr1.count);
        [self.tableview1 reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"网络请求出错");
    }];
}

- (void)requestForTableView2
{
    NSString *string = @"https://chanyouji.com/api/articles.json?page=1";
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    NSMutableArray *array = [NSMutableArray array];
    [manager GET:string parameters:self success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        for (NSMutableDictionary *dic in responseObject) {
            Special *note = [[Special alloc]init];
            [note setValuesForKeysWithDictionary:dic];
            [array addObject:note];
        }
        
        for (NSInteger i = array.count; i > 0; i--) {
            Special *ped = [array objectAtIndex:i-1];
            [self.arr2 addObject:ped];
        }
        
        
       // NSLog(@"%ld",self.arr2.count);
        [self.tableview2 reloadData];
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
     //???网络出现错误时候可以给提示
        
        
    }];
}




- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.tableview1) {
        return self.arr1.count;
    }else if (tableView == self.tableview2){
        return self.arr2.count;
    }else{
        return 0;
    }
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.tableview1) {
        static NSString *str = @"hehe";
        TravelTableViewCell *cell = [self.tableview1 dequeueReusableCellWithIdentifier:str];
        if (cell == nil) {
            cell = [[TravelTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str];
        }
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        Travelnote *notes = [self.arr1 objectAtIndex:indexPath.row];
        cell.notes = notes;
        cell.userButton.tag = indexPath.row;
        cell.targetAction = self;
        
        return cell;
        
        
    }else if (tableView == self.tableview2){
        
        static NSString *str2 = @"heheh";
        SpeacialTableViewCell *cell = [self.tableview2 dequeueReusableCellWithIdentifier:str2];
        if (cell == nil) {
            cell = [[SpeacialTableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:str2];
        }
         cell.selectionStyle = UITableViewCellSelectionStyleNone;
        Special *spe = [self.arr2 objectAtIndex:indexPath.row];
        cell.spe = spe;
       // Travelnote *notes = [self.arr1 objectAtIndex:indexPath.row];
       // cell.notes = notes;
        
        return cell;
        
    }
    
    return nil;
}

- (void)clickUser:(UIButton *)button
{
    Travelnote *usernote = [self.arr1 objectAtIndex:button.tag];
    UserViewController *user = [[UserViewController alloc]init];
    
    NSNumber *nu = [usernote.user objectForKey:@"id"];
    NSString *str = [NSString stringWithFormat:@"%@",nu];
    NSString *title = [usernote.user objectForKey:@"name"];
    user.hidesBottomBarWhenPushed = YES;
    user.userID = str;
    user.gaTitle = title;
    NSLog(@"按钮Tag值: %ld , 用户ID : %@",button.tag,str);
    [self.navigationController pushViewController:user animated:YES];
    
}



- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    
   // self.traveCell = (TravelCell *)[tableView cellForRowAtIndexPath:indexPath];
    
    
    return 160;
    
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.tableview1) {
   
        Travelnote *note = [self.arr1 objectAtIndex:indexPath.row];
        DetailViewController *detal = [[DetailViewController alloc]init];
        detal.hidesBottomBarWhenPushed = YES;
        detal.IDNumber = note.ID;
        [self.navigationController pushViewController:detal animated:YES];

    }
    
    if (tableView == self.tableview2) {
        
        Special *spe = [self.arr2 objectAtIndex:indexPath.row];
        ZuantiDetailViewController *zuan = [[ZuantiDetailViewController alloc]init];
        NSString *str = [NSString stringWithFormat:@"%@",spe.ID];
        
        zuan.urlStr = str;
        
        [self.navigationController pushViewController:zuan animated:YES];
    }
    
    
}






- (void)createRefreash
{
    [self.tableview1 addHeaderWithTarget:self action:@selector(headRefreshing)];
    [self.tableview1 addFooterWithTarget:self action:@selector(footeRefreshing)];
    [self.tableview1 headerBeginRefreshing];
    
    [self.tableview2 addHeaderWithTarget:self action:@selector(headRefreshing1)];
    [self.tableview2 addFooterWithTarget:self action:@selector(footeRefreshing1)];
    [self.tableview2 headerBeginRefreshing];
    
    self.tableview1.headerPullToRefreshText = @"下拉刷新";
    self.tableview1.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableview1.headerRefreshingText = @"正在刷新中,请稍后";
    
    
    self.tableview1.footerPullToRefreshText = @"上拉加载更多数据";
    self.tableview1.footerReleaseToRefreshText = @"松开加载更多数据";
    self.tableview1.footerRefreshingText = @"正在加载中。。。";
    
    
    self.tableview2.headerPullToRefreshText = @"下拉刷新";
    self.tableview2.headerReleaseToRefreshText = @"松开马上刷新了";
    self.tableview2.headerRefreshingText = @"正在刷新中,请稍后";
    
    
    self.tableview2.footerPullToRefreshText = @"上拉加载更多数据";
    self.tableview2.footerReleaseToRefreshText = @"松开加载更多数据";
    self.tableview2.footerRefreshingText = @"正在加载中。。。";
    
}


- (void)headRefreshing
{
    if (self.arr1.count == 0) {
        [self requestForTableView1];
    }
    
    
    //自动刷新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableview1 reloadData];
              // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [self.tableview1 headerEndRefreshing];
        
    });
    
}

- (void)headRefreshing1
{
   
    if (self.arr2.count == 0) {
        [self requestForTableView2];
    }
    
    //自动刷新
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        
        [self.tableview2 reloadData];
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
       
        [self.tableview2 headerEndRefreshing];
    });
    
}



- (void)footeRefreshing
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableview1 reloadData];
        NSString *string = [NSString stringWithFormat:@"%ld",(long)self.shu];
        NSString *str = [NSString stringWithFormat:@"https://chanyouji.com/api/trips/featured.json?page=%@",string];
        
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        
        [manager GET:str parameters:self success:^(AFHTTPRequestOperation *operation, id responseObject) {
            for (NSMutableDictionary *dic in responseObject) {
                Travelnote *note = [[Travelnote alloc]init];
                [note setValuesForKeysWithDictionary:dic];
                [self.arr1 addObject:note];
            }
            [self.tableview1 reloadData];
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            // NSLog(@"error: %@",error);
        }];
        
        
        [self.tableview1 footerEndRefreshing];
        self.shu += 1;
    });
    
    
}

- (void)footeRefreshing1
{
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(2.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        // 刷新表格
        [self.tableview2 reloadData];
        NSString *string = [NSString stringWithFormat:@"%ld",(long)self.shu1];
        NSString *str = [NSString stringWithFormat:@"https://chanyouji.com/api/articles.json?page=%@",string];
        
        
        AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
        
        [manager GET:str parameters:self success:^(AFHTTPRequestOperation *operation, id responseObject) {
            for (NSMutableDictionary *dic in responseObject) {
                Special *note = [[Special alloc]init];
                [note setValuesForKeysWithDictionary:dic];
                [self.arr2 addObject:note];
            }
            [self.tableview2 reloadData];
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            // NSLog(@"error: %@",error);
        }];
        
        
        [self.tableview2 footerEndRefreshing];
        self.shu1 += 1;
    });
    
    
}




- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
